package com.opencee.cloud.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.opencee.boot.db.mybatis.service.impl.SupperServiceImpl;
import com.opencee.cloud.base.constants.BaseConstants;
import com.opencee.cloud.base.entity.BaseDictEntity;
import com.opencee.cloud.base.mapper.BaseDictMapper;
import com.opencee.cloud.base.service.IBaseDictService;
import com.opencee.cloud.base.vo.BaseDictItemVO;
import com.opencee.common.exception.BaseFailException;
import com.opencee.common.utils.RedisTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 系统管理-数据字典 服务实现类
 * </p>
 *
 * @author liuyadu
 * @since 2021-04-16
 */
@Service
public class DictServiceImpl extends SupperServiceImpl<BaseDictMapper, BaseDictEntity> implements IBaseDictService {
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 获取字典单项值
     *
     * @param sid
     * @param category 字典编号
     * @param key      字典序号
     * @return
     */
    @Override
    public String getValue(String sid, String category, String key) {
        String cacheKey = BaseConstants.CACHE_DICT_VALUE + sid + ":" + category + "_" + key;
        if (redisTemplateUtil.hasKey(cacheKey)) {
            return redisTemplateUtil.getString(cacheKey);
        }
        String value = baseMapper.getValue(sid, category, key);
        if (value != null) {
            redisTemplateUtil.set(cacheKey, value, 2, TimeUnit.HOURS);
        } else {
            // 防止数据穿透
            redisTemplateUtil.set(cacheKey, value, 1, TimeUnit.MINUTES);
        }
        return value;
    }

    /**
     * 获取字典表
     *
     * @param
     * @param category 字典编号
     * @return
     */
    @Override
    public List<BaseDictItemVO> list(String sid, String category) {
        String cacheKey = BaseConstants.CACHE_DICT_LIST + sid + ":" + category;
        if (redisTemplateUtil.hasKey(cacheKey)) {
            return (List<BaseDictItemVO>) redisTemplateUtil.get(cacheKey);
        }
        List<BaseDictItemVO> value = baseMapper.getList(sid, category);
        if (value != null) {
            redisTemplateUtil.set(cacheKey, value, 2, TimeUnit.HOURS);
        } else {
            // 防止数据穿透
            redisTemplateUtil.set(cacheKey, value, 1, TimeUnit.MINUTES);
        }
        return value;
    }

    /**
     * 检验是否存在
     *
     * @param sid
     * @param category
     * @param key
     * @return
     */
    @Override
    public boolean exists(String sid, String category, String key) {
        QueryWrapper<BaseDictEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda()
                .eq(BaseDictEntity::getSid, sid)
                .eq(BaseDictEntity::getCategory, category)
                .eq(BaseDictEntity::getKey, key);
        return baseMapper.selectCount(queryWrapper) > 0;
    }


    @Override
    public boolean save(BaseDictEntity dict) {
        if (exists(dict.getSid(), dict.getCategory(), dict.getKey())) {
            throw new BaseFailException("字典:category=" + dict.getCategory() + ",key=" + dict.getKey() + "已存在");
        }
        String cacheKey = BaseConstants.CACHE_DICT_LIST + dict.getSid() + ":" + dict.getCategory();
        String cacheKey2 = BaseConstants.CACHE_DICT_VALUE + dict.getSid() + ":" + dict.getCategory() + "_" + dict.getKey();
        if (dict.getStatus() == null) {
            dict.setStatus(1);
        }
        dict.setDeleted(0);
        boolean flag = baseMapper.insert(dict) > 0;
        if (flag) {
            redisTemplateUtil.del(cacheKey, cacheKey2);
        }
        return flag;
    }

    @Override
    public boolean updateById(BaseDictEntity dict) {
        BaseDictEntity saved = getById(dict.getId());
        if (saved == null) {
            throw new BaseFailException("信息不存在!");
        }
        if (!saved.getCategory().equals(dict.getCategory()) || !saved.getKey().equals(dict.getKey())) {
            // 和原来不一致重新检查唯一性
            if (exists(dict.getSid(), dict.getCategory(), dict.getKey())) {
                throw new BaseFailException("字典:category=" + dict.getCategory() + ",key=" + dict.getKey() + "已存在");
            }
        }
        String cacheKey = BaseConstants.CACHE_DICT_LIST + dict.getSid() + ":" + dict.getCategory();
        String cacheKey2 = BaseConstants.CACHE_DICT_VALUE + dict.getSid() + ":" + dict.getCategory() + "_" + dict.getKey();
        boolean flag = baseMapper.updateById(dict) > 0;
        if (flag) {
            redisTemplateUtil.del(cacheKey, cacheKey2);
        }
        return flag;
    }

    @Override
    public boolean removeById(Serializable id) {
        BaseDictEntity dict = getById(id);
        boolean flag = baseMapper.deleteById(id) > 0;
        if (dict != null && flag) {
            String cacheKey = BaseConstants.CACHE_DICT_LIST + dict.getSid() + ":" + dict.getCategory();
            String cacheKey2 = BaseConstants.CACHE_DICT_VALUE + dict.getSid() + ":" + dict.getCategory() + "_" + dict.getKey();
            redisTemplateUtil.del(cacheKey, cacheKey2);
        }
        return flag;
    }

    @Override
    public BaseDictEntity getById(Serializable id) {
        return baseMapper.selectById(id);
    }
}
